package com.xyz.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyz.yygh.cmn.mapper.DictMapper;
import com.xyz.yygh.cmn.service.DictService;
import com.xyz.yygh.cmn.utils.DictListener;
import com.xyz.yygh.common.util.BeanUtils;
import com.xyz.yygh.model.cmn.Dict;
import com.xyz.yygh.vo.cmn.DictEeVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper , Dict> implements DictService {
    // 根据id查找子数据列表 @Cacheable: 其返回结果进行缓存，下次请求时，如果缓存存在，则直接读取缓存数据
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long parent_id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parent_id);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        for (Dict dict:dictList){
            String dictId = dict.getId();
            dict.setKey(dictId);
            boolean hasChildren = this.isHasChildren(dictId);
            dict.setHasChildren(hasChildren);
            dict.isLeaf = !hasChildren;
            dict.setTitle(dict.getName());
        }
        return  dictList;
    }
    // 导出表格
    @Override
    public void exportData(HttpServletResponse httpServletResponse) {
        try {
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            httpServletResponse.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            List<Dict> dictList = baseMapper.selectList(null);
            // 新建一个数组,将接口查到的数据复制进去
            ArrayList<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Dict dict:dictList){
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyBean(dict,dictVo,DictEeVo.class);
                dictVoList.add(dictVo);
            }
            EasyExcel.write(httpServletResponse.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictVoList);

        }catch (IOException e){
            e.printStackTrace();
        }
    }
    // 导入数据字典 allEntries = true: 方法调用后清空所有缓存
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importDictData(MultipartFile file) {
            try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();

            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    // 判断是否有子集
    private boolean isHasChildren(String parent_id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parent_id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return  count>0;
    }
}
